package com.wocao.config;

import com.wocao.entity.ResponseResult;
import com.wocao.utils.JwtUtils;
import com.wocao.utils.RsaUtils;
import com.wocao.utils.log.LoginLog;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 登录成功处理器
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    //验证成功后的回调
    @LoginLog
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        //获得登录后的用户名
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user == null) {
            throw new RuntimeException("用户为空");
        }

        //生成accessToken
        String accessToken = JwtUtils.generateToken(user.getUsername(), RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
        //截取一部分，生成refreshToken
        String uid = accessToken.substring(0,10);
        String refreshToken = JwtUtils.generateToken(uid, RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES * 2);
        HashMap<String,String> tokens = new HashMap<>();
        tokens.put("accessToken",accessToken);
        tokens.put("refreshToken",refreshToken);
        //将两个token发送给前端
        ResponseResult.write(ResponseResult.ok(tokens),httpServletResponse);
    }
}
